package org.jgs1904.apachepoidemo.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;

import java.io.File;
import java.io.IOException;

/**
 * 获取单元格内容
 *
 * @author: 默苍璃
 * @date: 2023-10-09 15:07
 */
public class GetCell {

    public static void main(String[] args) throws IOException {
        // Use a file
        Workbook wb = WorkbookFactory.create(new File("D:\\temp\\xssf-align.xlsx"));

        // import org.apache.poi.ss.usermodel.*;
        DataFormatter formatter = new DataFormatter();
        Sheet sheet1 = wb.getSheetAt(0);
        for (Row row : sheet1) {
            for (Cell cell : row) {
                System.out.println("行：" + row.getRowNum());
                System.out.println("列：" + cell.getColumnIndex());
                CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
                System.out.print(cellRef.formatAsString());
                System.out.print(" - ");
                // get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc)
                String text = formatter.formatCellValue(cell);
                System.out.println(text);
                // Alternatively, get the value and format it yourself
                switch (cell.getCellType()) {
//                    case CellType.STRING:
                    case STRING:
                        System.out.println(cell.getRichStringCellValue().getString());
                        break;
//                    case CellType.NUMERIC:
                    case NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            System.out.println(cell.getDateCellValue());
                        } else {
                            System.out.println(cell.getNumericCellValue());
                        }
                        break;
//                    case CellType.BOOLEAN:
                    case BOOLEAN:
                        System.out.println(cell.getBooleanCellValue());
                        break;
//                    case CellType.FORMULA:
                    case FORMULA:
                        System.out.println(cell.getCellFormula());
                        break;
//                    case CellType.BLANK:
                    case BLANK:
                        System.out.println();
                        break;
                    default:
                        System.out.println();
                }
            }
        }

    }


}
